<template>
  <view class="rank-list">
    <view class="table-header" :style="{ gridTemplateColumns: gridTemplateColumns, gap: '24rpx' }">
      <view v-for="column in columns" :key="column.key" class="header-cell">
        <template v-if="$slots.title">
          <slot name="title" :column="column"></slot>
        </template>
        <template v-else>
          <view :style="{ textAlign: column.align || 'center' }">
            {{ column.title }}
          </view>
        </template>
      </view>
    </view>
    <view class="table-body">
      <view
        v-for="(row, index) in rows"
        :key="row.id"
        class="table-row"
        :style="{
          gridTemplateColumns: gridTemplateColumns,
          gap: '24rpx',
          background: row['currentUserRankNum'] ? '#FFF4E7' : '',
        }"
      >
        <view
          v-for="column in columns"
          :key="`${row.id}-${column.key}`"
          class="data-cell"
          :style="{
            textAlign: column.align || 'center',
          }"
        >
          <template v-if="$slots.row">
            <slot name="row" :row="row" :column="column" :rows="rows" :index="index"></slot>
          </template>
          <template v-else>
            {{ row[column.key] }}
          </template>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue';

  export interface Column {
    title: string;
    key: string;
    width?: string;
    align?: 'left' | 'center' | 'right';
  }

  const props = defineProps({
    rows: {
      type: Array as () => Record<string, any>[],
      default: () => [],
    },
    columns: {
      type: Array as () => Column[],
      default: () => [],
    },
  });

  const gridTemplateColumns = computed(() => {
    return props.columns
      .map((column) => {
        if (column.width === 'auto') {
          return '1fr';
        }
        return column.width;
      })
      .join(' ');
  });
</script>

<style lang="scss" scoped>
  .rank-list {
    display: grid;
    width: 100%;

    .table-header {
      display: grid;
      padding: 24rpx;
      gap: 24rpx;
    }
    .table-body .table-row {
      display: grid;
      padding: 24rpx;
    }

    .header-cell,
    .data-cell {
      box-sizing: border-box;
    }
    .data-cell {
      display: flex;
      align-items: center;
    }
    .data-cell {
      ::v-deep > view {
        flex: 1;
      }
    }
    .header-cell {
      color: #999996;
      font-size: 24rpx;
      font-weight: 400;
      line-height: 32rpx;
    }
  }
</style>
